<?php
App::uses('CakeEmail', 'Network/Email');
class SecurityController extends AppController {
  public $helpers = array('Html', 'TWSForm');
  public $components = array('Session', 'Util');
  public $name = 'Security';

  function login() {
   $userLoggedIn = $this->Session->read('User');
    if(!empty($userLoggedIn)) {
      //determining profile to load
      foreach(Configure::read('App.userRoles') as $index=>$userRole) {
        if(in_array($userRole, $userLoggedIn['UserRoles'])){
          $this->redirect('/'.$userRole);
        }
      }
    }
    $this->set('title_for_layout','Isle Vow Login');
    if ($this->request->is('post')) {
      $this->loadModel('Login');
      $this->loadModel('User');
      $inputData = $this->_processRequestData($this->request);
      $inputData = $inputData['Security'];
      $login = array();
      $login['Login']=array();
      $login['Login']['email']=$inputData['email'];
      $login['Login']['password']=$inputData['password'];
      $test = sha1($login['Login']['password']);
      $this->Login->set($login);
      if($this->Login->validates()) {
        $user = $this->User->find("first", array('conditions' => array("User.email" => $login['Login']['email'], "User.password"=>sha1($login['Login']['password']))));
        if(!empty($user)) {
          if($user['User']['verified']!='Y') {
              //Sending verification email
              App::import('Helper', 'Html');
              $view = new View($this);
              $html = $view->loadHelper('Html');
              $url = FULL_BASE_URL.$html->url(array('action'=>'resendVerification',$user['User']['email']));
            $this->Session->setFlash('Your email address has not been verified by the system. An email would have been sent to '. $user['User']['email'] . ' with instructions on how to verify your account.<br/><br/>If you did not receive this email, you can <a href="'.$url.'">request to send this verification email</a> again.');
          } elseif ($user['User']['active']!='Y') {
            $this->Session->setFlash('Your account has been disabled. Please contact your site administrator to reactivate your account.');
          } elseif (empty($user['User']['first_activated'])) {
            $this->Session->setFlash('Your account is still in the process of being activated. An email will be sent to you from the site administator when the activation process is complete.');
          } else {
            $userRoles = array();
            //Getting User roles
            foreach($user['Role'] as $role){
              array_push($userRoles, $role['role_name']);
            }
            $user['UserRoles']=$userRoles;
            $this->Session->write('User',$user);
            $destinationUrl = $this->Session->read('destinationUrl');
            if (isset($destinationUrl)) {
              $this->Session->delete('destinationUrl');
              $this->redirect('/'.$destinationUrl);
            } else {
              foreach(Configure::read("App.userRoles") as $index=>$userRole) {
                if(in_array($userRole, $userRoles)){
                  $this->redirect("/".$userRole);
                }
              }
              $this->redirect("/"); //Redirect to Home Page -- Should never get here
            }
          }
        } else {
          $this->Session->setFlash('Invalid email address and password');
        }
      } else {
        $this->set('errors', $this->Passcode->validationErrors);
      }
    }
  }

  function resendVerification($account) {
    if(!empty($account)) {
      $this->loadModel('User');
      $user = $this->User->find("first", array('conditions' => array("User.email" =>$account)));
      if($user['User']['verified']!='Y') {
        $result = $this->_sendVerificationEmail($user);
        if($result){
          $this->Session->setFlash('An email was resent to verify your email account. Please wait a few minutes before checking for the email and follow the instructions to complete the registration process.' );
        } else {
          $this->Session->setFlash('An error occurred and your verification email could not be sent. Please try again.' );
        }
      } else {
        $this->Session->setFlash('Your account and email address has already been verified. You may log into the system.');
      }

      $this->render('login');
    } else {
     throw new NotFoundException();
    }
  }

  function admin_logout() {
    $this->Session->delete('User');
    $this->redirect("/");
  }

  function photographer_logout() {
    $this->admin_logout();
  }

  function admin_resetPassword() {
    $this->resetPassword("admin");
    $this->render('admin_reset_password');
  }
  
  function photographer_resetPassword() {
    $this->resetPassword("photographer");
    $this->render('admin_reset_password'); //same view
  }

  private function resetPassword($profile) {
    if($profile){
      $this->layout = $profile;
      $this->set('title_for_layout','Reset '. $profile .' password');
      if($this->request->is('post')) {
        $this->loadModel("User");
        $inputData = $this->_processRequestData($this->request);
        $user = $this->Session->read("User");
        $data= array("User" => array("id"=>$user['User']['id'],"password"=>sha1($inputData['Security']['password'])));
        $result=$this->User->save($data, false, array('password'));
        if(!empty($result)){
          $this->Session->setFlash('Your password was successfully reset.');
        } else {
          throw new Exception("An error has occurred and your password was not updated. Please try again!");
        }
      }
    } else {
      throw new NotFoundException();
    }
  }

  function register() {
    $this->set('title_for_layout','Account Registration');
    if($this->request->is('post')){
      $this->loadModel('Passcode');
      $inputData = $this->_processRequestData($this->request);
      $data=array();
      $data['Passcode']=array();
      $data['Passcode']['id']=$inputData['Security']['passcode'];
      $this->Passcode->set($data);
   //   if($this->Passcode->validates()){
      $passcode =$this->Passcode->find("first", array('conditions' => array("Passcode.id" => $data['Passcode']['id'])));
      if(!empty($passcode)) {
        $this->Session->write('Register', $passcode);
        $this->redirect(array('action'=>'registerAccount'));
      } else {//TODO : set validation error
       $this->set('errors', array("passcode"=>array("You have entered an invalid passcode!")));
     }
    } else {
      $register = $this->Session->read('Register');
      if(isset($register)) {
        $this->redirect(array('action'=>'registerAccount'));
      }
    }
  }

  function admin_passcode() {
    $this->layout = "admin";
    $this->set('title_for_layout','Change Passcode');
    $this->loadModel('Passcode');
    if($this->request->is('post')){  
      $inputData = $this->_processRequestData($this->request);
      $result = $this->Passcode->deleteAll(array("active"=>'Y'));
      if($this->Passcode->save(array('id' =>$inputData['Security']['passcode']),false ,array("id"))){
        $this->Session->setFlash('The passcode was successfully changed.');
      } else {
        $this->Session->setFlash('An error occurred and the passcode was not successfully changed. Please try again');
      }
    }
      $passcode = $this->Passcode->find('first');
      $this->set('passcode',$passcode);
  }

  function accountVerification() {
    $this->set('title_for_layout','Account verification');
    $account = $this->request->params['named']['id'];
    $verificationCode = $this->request->params['named']['auth'];
    if (empty($account) || empty($verificationCode)) {
      throw new NotFoundException('This is not a valid url');
    } else {
     $this->loadModel('User');
      $user = $this->User->find("first", array('conditions' => array("User.email" =>$account, "User.verification_code"=>$verificationCode)));
      if(empty($user)) {
        throw new NotFoundException('This is not a valid url');
      } else {
        if ($user['User']['verified']=='Y') {
          $this->Session->setFlash('This user account and email address has already been verified.');
        }else {
          //update account
          //$this->User->id=$user['User']['id'];
          $date= new DateTime();
          $data=array('User'=>array('id'=>$user['User']['id'],'verified'=>'Y', 'first_activated'=>null));
          $message = 'Your email address has been verified. Additional processing must occur before your account setup is complete. You will receive an email from the site administrator within the next (2) business days when your account has been activated.';
          if(!empty($user['Role'])) {
            $userRoles = Configure::read("App.userRoles");
            if ($user['Role'][0]['role_name']===Configure::read("App.adminRole") || $user['Role'][0]['role_name']==$userRoles['member']){
              $data['User']['first_activated']=$date->format('Y-m-d');
              $message = 'Your email address has been verified. You may now proceed to login.';
            } else {
              //sending email notification
              $this->_sendActivationNotificationEmail($user);
            }
          }
          
          $result=$this->User->save($data, false, array('verified','first_activated'));
          $this->Session->setFlash($message);
        }
      }
    }
    $this->render('login');
  }

  function registerAccount() {
    $register = $this->Session->read('Register');
    if(isset($register)) {
      $this->set('title_for_layout','Account Registration');
      if ($this->request->is('post')) {
        //TODO : Validation check
        $this->loadModel('User');
        $inputData = $this->_processRequestData($this->request);
        $inputData = $inputData['Security'];
        $verificationCode = $this->_getRandomString(15);
        $data = array();
        $data['User']=array();
        $data['User']['description']=$inputData['description'];
        $data['User']['first_name']=$inputData['first_name'];
        $data['User']['last_name']=$inputData['last_name'];
        $data['User']['email']=$inputData['email'];
        $data['User']['password']=$inputData['password'];
        $data['User']['verification_code']=$verificationCode;
        $this->User->set($data);
        if ($this->User->validates()) {
          //encrypt the password
          $data['User']['password']=sha1($data['User']['password']);
          if ($this->User->save($data, false)) {
            //setting up the role for the Admin
            $this->loadModel('UserRoles');
            $roleData=array();
            $roleData['UserRoles']=array();
            $roleData['UserRoles']['user_id']=$this->User->id;
            //Determining type of passcode that was registered
            $roleData['UserRoles']['role_name']=$register['Passcode']['role_name'];
            if ($this->UserRoles->save($roleData)) {
              //send email
              $this->_sendVerificationEmail($data);
              $this->Session->setFlash('Thank you for registering. In order to verify your email address, an email was sent to the address you specified. Please follow the instructions to complete the registration process.');
              $this->Session->delete('Register');
               $this->render('login');
            } else {
              $this->Session->setFlash('There was an error in registering your account. Can you please try again.');
            }
          }

        } else { //Validation did not occur
          $data['User']['password']="";
           $this->request->data['Security'] = $data['User'];
          $this->set('errors', $this->User->validationErrors);
        }
      } else {
        $register = $this->Session->read('Register');
        if(!isset($register )) {
          $this->redirect(array('action'=>'register'));
        }
      }
    } else {
       $this->redirect('register');
    }
  }


  function signup() {
      $this->set('title_for_layout','Member Sign Up');
      if ($this->request->is('post')) {
        $this->loadModel('User');
        $inputData = $this->_processRequestData($this->request);
        $inputData = $inputData['Security'];
        $verificationCode = $this->_getRandomString(15);
        $data = array();
        $data['User']=array();
        $data['User']['first_name']=$inputData['first_name'];
        $data['User']['last_name']=$inputData['last_name'];
        $data['User']['email']=$inputData['email'];
        $data['User']['password']=$inputData['password'];
        $data['User']['verification_code']=$verificationCode;
        $this->User->set($data);
        if ($this->User->validates()) {
          //encrypt the password
          $data['User']['password']=sha1($data['User']['password']);
          if ($this->User->save($data, false)) {
            //setting up the role for the Admin
            $this->loadModel('UserRoles');
            $roleData=array();
            $roleData['UserRoles']=array();
            $roleData['UserRoles']['user_id']=$this->User->id;
            //Determining type of passcode that was registered
            $userRoles = Configure::read("App.userRoles");
            $roleData['UserRoles']['role_name']=$userRoles["member"];
            if ($this->UserRoles->save($roleData)) {
              //send email
              $this->_sendVerificationEmail($data);
              $this->Session->setFlash('Thank you for signing up. In order to verify your email address, an email was sent to the address you specified. Please follow the instructions to complete the registration process.');
               $this->render('login');
            } else {
              $this->Session->setFlash('An error occurred while setting up your account. Can you please try again.');
            }
          }

        } else { //Validation did not occur
          $data['User']['password']="";
           $this->request->data['Security'] = $data['User'];
          $this->set('errors', $this->User->validationErrors);
        }
      }
  }

  function _sendVerificationEmail($user) {
    $retVal = false;
     if (is_array($user)){
      $data = $user;
      //Sending verification email
      App::import('Helper', 'Html');
      $view = new View($this);
      $html = $view->loadHelper('Html');
      $url = FULL_BASE_URL.$html->url(array('action'=>'accountVerification','id'=>$data['User']['email'],'auth'=>$data['User']['verification_code']));
      $email = new CakeEmail('tws');
      $email->to($data['User']['email'],$data['User']['first_name'].' '.$data['User']['last_name']);
      $email->subject("Verification for registration at the ".Configure::read('App.name'). " website");
      $email->template('activateLogin');
      $email->from(array(Configure::read('App.emailDefaultFrom')=>Configure::read('App.name')));
      $email->transport('Debug')->viewVars(array('name'=>$data['User']['first_name'].' '.$data['User']['last_name'],'clubName'=>Configure::read('App.name'),'verificationLink' => $url));
      $retVal = $email->send();
    }
    return $retVal;
  }

    function _sendActivationNotificationEmail($user) {
    $retVal = false;
     if (is_array($user)){
      $data = $user;
      //Sending verification email
      App::import('Helper', 'Html');
      $view = new View($this);
      $html = $view->loadHelper('Html');
      $email = new CakeEmail('tws');
      $email->to(Configure::read('App.emailDefaultTo'),'Isle Vow Site Administrator');
      $email->subject("Account activation required at the ".Configure::read('App.name'). " website");
      $email->template('activate_account_notification');
      $email->from(array(Configure::read('App.emailDefaultFrom')=>Configure::read('App.name')));
      $email->transport('Mail')->viewVars(array('name'=>$user['User']['first_name'].' '.$user['User']['last_name'],'clubName'=>Configure::read('App.name'),'email'=>$user['User']['email']));
      $retVal = $email->send();
    }
    return $retVal;
  }

  function forgotPassword() {
    $this->set('title_for_layout','Forgot your password');
    if($this->request->is('post')){
     $this->loadModel('User');
     $inputData = $this->_processRequestData($this->request);
      $user = $this->User->find("first", array('conditions' => array("User.email" =>$inputData['Security']['email'])));
      if(!empty($user)) {
        $newPassword = $this->_getRandomString(5);
        $data= array("User" => array("id"=>$user['User']['id'],"password"=>sha1($newPassword)));
        $result=$this->User->save($data, false, array('password'));
        if(!empty($result)) {
          //send email
          $email = new CakeEmail('tws');
          $email->to($user['User']['email'],$user['User']['first_name'].' '.$user['User']['last_name']);
          $email->subject("Password request notification from the ".Configure::read('App.name'). " website");
          $email->template('forgotPassword');
          $email->from(array(Configure::read('App.emailDefaultFrom')=>Configure::read('App.name')));
          $email->transport('Mail')->viewVars(array('name'=>$user['User']['first_name'].' '.$user['User']['last_name'],'clubName'=>Configure::read('App.name'),'newPassword' => $newPassword));
          $retVal = $email->send();
          $this->Session->setFlash('Your password was successfully reset.');
        } else {
          CakeLog::error("The password was not successfully reset for user : [".$user['User']['id']."][".$user['User']['email']."]");
          $this->Session->setFlash('A problem occurred and your password was not successfully reset. Please try again.');
        }
      } else {
        $this->Session->setFlash('Please specify a valid Email.');
      }
      //reset password
      //send out email
    }
  }

  function _getRandomString($length = "")
  {
    $code = md5(uniqid(rand(), true));
    if ($length != "") return substr($code, 0, $length);
    else return $code;
  }

  }
  
  ?>